package cn.wit.sst.service;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import cn.wit.sst.domain.Major;
import cn.wit.sst.dto.ClazzQuery;
import cn.wit.sst.dto.ScoreRankDto;
import cn.wit.sst.mapper.MajorMapper;
import cn.wit.sst.mapper.ScoreMapper;
import cn.wit.sst.utils.Utils;

@Service
@Transactional
public class ClazzService {

	@Autowired
	MajorMapper majorMapper;

	@Autowired
	ScoreMapper scoreMapper;

	public List<Major> selectMajorByCollegeId(Long id) {
		return majorMapper.selectByCollegeId(id);
	}

	public Map<Long, List<ScoreRankDto>> search(ClazzQuery query) {
		int examYear = query.getGrade() + query.getYear();		// 学年

		List<ScoreRankDto> scores = scoreMapper.getScoreRanksForClazz(query.getMid(),
				query.getYear(),
				examYear,
				query.getSemester(),
				query.getClazz());

		// 将各课程分数分组		（key为课程id，value为所有学生该课程的分数集合）
		Map<Long, List<ScoreRankDto>> map = scores.stream()
				.collect(Collectors.groupingBy(ScoreRankDto::getCid));

		// 遍历每一学科，计算排名
		map.forEach((key, value) -> {
			Utils.computeRank(value);
		});

		return map;
	}
}
